package redis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import entity.custom.CustomImage;
import entity.custom.CustomText;
import entity.custom.Image;
import entity.custom.Text;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import service.WxServiceImpl;
import service.api.ai.AiService;
import service.api.ai.ERNIE_ViLG;
import util.Request;

import java.io.InputStream;
import java.util.Map;
import java.util.Set;

@Slf4j
public class MessageConsumerImage implements Runnable {
    static InputStream in = MessageConsumerImage.class.getClassLoader().getResourceAsStream("wx-config.xml");
    static Map<String, String> Xmlmap = WxServiceImpl.parseRequest(in);
    private static final String UploadUrl = Xmlmap.get("uploadUrl");
    private static final String CustomSend=Xmlmap.get("customSend");
    static JedisConnectPool jedisPool = new JedisConnectPool();
    static Jedis jedis=jedisPool.getJedis();
    static Jedis jedis2=jedisPool.getJedis();
    public static final String CHANNEL_KEY = "task_que";//频道
    public static final String EXIT_COMMAND = "exit";//结束程序的消息

    private final MyJedisPubSub jedisPubSub = new MyJedisPubSub();
    public void consumerMessage() {
        jedis.psubscribe(jedisPubSub, CHANNEL_KEY);
    }

    @Override
    public void run() {
//        while (true) {
            consumerMessage();
//        }
    }


    public static void main(String[] args) {
        MessageConsumerImage mc = new MessageConsumerImage();
        Thread t1 = new Thread(mc, "Listen_task_que");

        t1.start();
    }


    static class MyJedisPubSub extends JedisPubSub {
//        ERNIE_ViLG ernie_viLG=new ERNIE_ViLG();
        @Override
        public void onMessage(String channel, String message) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPMessage(String pattern, String channel, String message) {
            System.out.println(Thread.currentThread().getName() + "-接受到的消息:pattern"+pattern+",channel:"+channel+",message:"+message);
            String[] s = message.split(":");
            String uploadUrl=UploadUrl.replace("ACCESS_TOKEN",WxServiceImpl.getAccessToken()).replace("TYPE","image");
            String customSendUrl=CustomSend.replace("ACCESS_TOKEN",WxServiceImpl.getAccessToken());
            //文心模型
//            Set<String> images=ernie_viLG.getImg(s[1]);
            //GPT模型
            JSONArray images;
            try {
                images = AiService.imageChat(s[1]);
            } catch (Exception e) {
                log.info("get:"+jedis2.smembers("openId_set")+"srem:"+ jedis2.srem("openId_set", s[0]));
                String sendData = JSONObject.toJSONString(new CustomText(s[0], new Text("画不出来，让我思考思考，过会再试试或联系鑫哥")));
                log.info("sendData  :" + sendData);
                String res = Request.sendPost(customSendUrl, sendData);
                log.info("customRes  :" + res);
                throw new RuntimeException(e);
            }

            for (String imagesUrl:images.toJavaList(String.class)) {
                try {
                    imagesUrl=JSONObject.parseObject(imagesUrl).getString("url");
                    log.info(imagesUrl);
                    JSONObject jsonObject=JSONObject.parseObject(Request.uploadPostUrl(uploadUrl,imagesUrl));
                    log.info("upload  :"+ jsonObject);
                    String mediaId=jsonObject.getString("media_id");
                    String sendData=JSONObject.toJSONString(new CustomImage(s[0],new Image(mediaId)));
                    log.info("sendData  :"+sendData);
                    String res= Request.sendPost(customSendUrl,sendData);
                    log.info("customRes  :"+res);

                }catch (Exception e){
                    log.error(e.getMessage(),e);
                }finally {
                    log.info("get:"+jedis2.smembers("openId_set")+"srem:"+ jedis2.srem("openId_set", s[0]));
                }

            }



//            if(MessageConsumer.EXIT_COMMAND.equals(message)){
//                System.exit(0);
//            }
        }

        @Override
        public void onSubscribe(String channel, int subscribedChannels) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onUnsubscribe(String channel, int subscribedChannels) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPUnsubscribe(String pattern, int subscribedChannels) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPSubscribe(String pattern, int subscribedChannels) {
            // TODO Auto-generated method stub

        }

    }
}
